<template>
  <div class="w-screen h-screen bg-black bg-g flex justify-center">
    <div class="w-full overflow-hidden" ref="wrapRef">
      <img ref="imgRef" :src="src" class="max-w-none" />
    </div>
  </div>
</template>
<script>
export default {
  name: "JcGePuFangYing",
  props: {
    src: {
      default: "",
      required: true,
    },
    options: {
      type: [Object, null],
      default: () => null,
    },
  },
  data() {
    return {
      maxHeight: window.innerHeight,
      maxWidth: document.body.clientWidth,
      prevSrc: "",
    };
  },
  mounted() {},
  methods: {
    previeChange() {
      console.log("previeChange", this.options);

      if (!this.options) {
        return;
      }
      if (!this.$refs.imgRef) {
        return;
      }

      const { data, imgData: imageData } = this.options;
      const elem = this.$refs.wrapRef;

      var previewAspectRatio = data.width / data.height;
      const previewImage = this.$refs.imgRef;
      let previewWidth = elem.offsetWidth;
      let previewHeight = Math.round(previewWidth / previewAspectRatio);
      let imageScaledRatio = data.width / previewWidth;
      console.log("previewHeight:", previewHeight, "maxHeight:", this.maxHeight);
      if (previewHeight >= this.maxHeight) {
        imageScaledRatio = data.height / this.maxHeight;
        previewHeight = this.maxHeight;
        previewWidth = this.maxHeight * previewAspectRatio;
        elem.style.width = previewWidth + "px";
        if (elem.style.margin.indexOf("auto") == -1) {
          // elem.style.margin = '0 auto'
        }
      } else {
        console.log("高度小于最大高度", elem.style.margin);
        console.log(previewHeight, this.maxHeight);
        elem.style.width = "100%";
        // elem.style.margin = 'none'
      }
      let prevHeight = imageData.naturalHeight / imageScaledRatio;
      let prevWidth = imageData.naturalWidth / imageScaledRatio;

      let marginLeft = -data.x / imageScaledRatio;
      let marginTop = -data.y / imageScaledRatio;
      elem.style.height = previewHeight + "px";

      if (this.src !== this.prevSrc) {
        console.log("不等于上一次的src", this.prevSrc);
        console.log(this.src);
      }

      const previewStyle = {
        width: prevWidth,
        height: prevHeight,
        marginLeft,
        marginTop,
      };

      for (let key of Object.keys(previewStyle)) {
        previewImage.style[key] = previewStyle[key] + "px";
      }

      this.prevSrc = this.src;
    },
  },
  watch: {
    options: function () {
      this.previeChange();
    },
  },
};
</script>

<style scoped>
.bg-g {
  background-image: linear-gradient(-225deg, #5d9fff 0%, #b8dcff 48%, #6bbbff 100%);
}
</style>
